package com.laity.demo2;

/**
 * @author: Laity
 * @Project: JavaLaity
 * @Package: com.laity.demo2.Communication01
 * @Date: 2023年11月22日 00:25
 * @Description: Synchronized版本 线程直接通信问题：生产者和消费者问题！ 等待唤醒，通知唤醒
 * 线程交替执行  t1 t2 两个线程操作同一个变量，进行 +1 | -1
 */

public class Communication01 {
    static Thread t1 = null, t2 = null, t3 = null, t4 = null;

    public static void main(String[] args) {
        Data data = new Data();
        t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1");

        t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t2");

        t3 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t3");

        t4 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

// 资源类：线程就是一个单独的资源类，没有附属的操作
// 判断等待、业务、通知
class Data {
    private int number = 0;

    // +1
    // 只要有并发就一定要加锁
    public synchronized void increment() throws InterruptedException {
        while (number != 0) {
            // 等待
            this.wait();
        }
        // 业务
        number++;
        // 加1后通知其它线程我加一完毕了
        System.out.println(Thread.currentThread().getName() + "==>" + number);
        this.notifyAll();
    }

    // -1
    public synchronized void decrement() throws InterruptedException {
        while (number == 0) {
            // 等待
            this.wait();
        }
        number--;
        // 通知其它线程我减一完毕了
        System.out.println(Thread.currentThread().getName() + "==>" + number);
        this.notifyAll();
    }
}
